/*
 * VoodooLoader.cpp
 *
 *  Created on: Apr 29, 2009
 *      Author: wrice
 */
#include <iostream>
#include <fstream>
#include <sstream>
#include "MyVideoTrace.h"
namespace MyVideoTrace {

VoodooLoader::VoodooLoader() {
}

bool VoodooLoader::loadCameraData( string filename ) {
	cameraInfos_.clear();

	ifstream inFile;
	inFile.open(filename.c_str());
	if( !inFile ) return false;

	char buff[1024];
	while( inFile ) {
		inFile.getline(buff, 1024);
		VoodooCameraInfo eachCamera;
		const bool succeed = eachCamera.parseCameraText(string(buff));
		if( false == succeed ) continue;
		cameraInfos_.push_back(eachCamera);
	}

	return true;
}

VoodooCameraInfo VoodooLoader::getCameraInfo( FrameNumber frameNumber ) const {
	return cameraInfos_.at(frameNumber);
}

FrameNumber VoodooLoader::getNumberOfCameraInfo() const {
	return cameraInfos_.size();
}

bool VoodooLoader::loadFeaturePoints( string prefix, int startNum, int endNum, string postFix, int step ) {
	featurePoints_.clear();

	char buf[1024];
	int frameNumber = 0;
	for( int idx = startNum; idx < endNum; idx += step ) {
		snprintf( buf, 1024, "%03d", idx );
		const string middlefix = buf;
		ifstream inFile;
		inFile.open( (prefix + middlefix + postFix).c_str() );
		if( !inFile ) return false;

		while( inFile ) {
			inFile.getline(buf, 1024);
			VoodooFPointInfo eachFPoint;
			const bool succeed = eachFPoint.parseFPointData(string(buf));
			if( false == succeed ) continue;

			const int id = eachFPoint.getFPointID();
			if( 0 == id ) continue;

			FeaturePointsIterator iter = featurePoints_.find( id );
			const bool newFeaturePoint = (iter == featurePoints_.end() );

			FeaturePointPtr fpoint;
			if( newFeaturePoint ) {
				fpoint = new FeaturePoint( id );
				fpoint->setPoint3D( eachFPoint.getXCoord(), eachFPoint.getYCoord(), eachFPoint.getZCoord() );
			} else {
				fpoint = iter->second;
				assert( fpoint->getX() == eachFPoint.getXCoord() );
				assert( fpoint->getY() == eachFPoint.getYCoord() );
				assert( fpoint->getZ() == eachFPoint.getZCoord() );
			}

			fpoint->setPoint2D( frameNumber, Point2D( eachFPoint.getXOffset(), eachFPoint.getYOffset() ) );

			featurePoints_.insert( FeaturePointsPair( id, fpoint ) );
		}

		++frameNumber;
	}

	return true;
}

size_t VoodooLoader::getNumberOfFeaturePoints() const {
	return featurePoints_.size();
}

FeaturePoint VoodooLoader::getFeaturePoint( size_t idx ) const {
	FeaturePointsIterator iter = featurePoints_.begin();
	for( size_t i = 0; i < idx && iter != featurePoints_.end(); ++i )
		++iter;
	return *(iter->second);
}


}
